package net.zoneland.zrdp.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.richercloud.lift.util.function.enhancer.FunctionEnhancer;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import net.zoneland.zrdp.common.annotation.DataScope;
import net.zoneland.zrdp.common.constant.UserConstants;
import net.zoneland.zrdp.common.core.domain.TreeSelect;
import net.zoneland.zrdp.common.core.domain.entity.SysDept;
import net.zoneland.zrdp.common.core.domain.entity.SysRole;
import net.zoneland.zrdp.common.core.domain.entity.SysUser;
import net.zoneland.zrdp.common.core.text.Convert;
import net.zoneland.zrdp.common.exception.ServiceException;
import net.zoneland.zrdp.common.utils.SecurityUtils;
import net.zoneland.zrdp.common.utils.spring.SpringUtils;
import net.zoneland.zrdp.system.mapper.SysDeptMapper;
import net.zoneland.zrdp.system.mapper.SysRoleMapper;
import net.zoneland.zrdp.system.service.ISysDeptService;

import javax.annotation.Resource;

/**
 * 部门管理 服务实现
 *
 * @author zonevue
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService {
    @Resource
    private SysDeptMapper deptMapper;

    @Resource
    private SysRoleMapper roleMapper;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(final SysDept dept) {
        return deptMapper.selectDeptList(dept);
    }

    /**
     * 查询部门管理数据排除子节点id
     *
     * @param deptId 部门信息id
     * @return 部门信息集合
     */
    @Override
    public List<SysDept> selectDeptListExpireChild(Long deptId) {
        return deptMapper.selectDeptListExpireChild(deptId);
    }

    /**
     * 查询部门树结构信息
     *
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeSelect> selectDeptTreeList(final SysDept dept) {
        final List<SysDept> depts = getAopProxy().selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(final List<SysDept> depts) {
        final Set<Long> tempList = depts.stream().map(SysDept::getDeptId).collect(Collectors.toSet());
        final List<SysDept> returnList = depts.stream()
            .filter(FunctionEnhancer.with(SysDept::getParentId).thenTest(tempList::contains).negate())// 找出所有一级菜单
            .map(dept -> {
                recursionFn(depts, dept); // 递归处理 会修改dept的子节点信息
                return dept;
            })
            .collect(Collectors.toList());

        if (returnList.isEmpty()) {
            return depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(final List<SysDept> depts) {
        final List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Long> selectDeptListByRoleId(final Long roleId) {
        final SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(final Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(final Long deptId) {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(final Long deptId) {
        return deptMapper.hasChildByDeptId(deptId);
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(final Long deptId) {
        return deptMapper.checkDeptExistUser(deptId);
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(final SysDept dept) {
        final long deptId = Objects.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        final SysDept info = deptMapper.selectOneByNameAndParentId(dept.getDeptName(), dept.getParentId());
        return Objects.isNull(info) || info.getDeptId() == deptId;
    }

    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(final Long deptId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            final SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            final List<SysDept> depts = getAopProxy().selectDeptList(dept);
            if (CollectionUtils.isEmpty(depts)) {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(final SysDept dept) {
        final SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return deptMapper.insertDept(dept);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(final SysDept dept) {
        final SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        final SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
        if (!Objects.isNull(newParentDept) && !Objects.isNull(oldDept)) {
            final String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            final String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }

        final int result = deptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(final SysDept dept) {
        final String ancestors = dept.getAncestors();
        final Long[] deptIds = Convert.toLongArray(ancestors);
        deptMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(final Long deptId, final String newAncestors, final String oldAncestors) {
        final List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        if (children.isEmpty()) {
            return;
        }
        children.forEach(child -> child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors)));
        deptMapper.updateDeptChildren(children);
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(final Long deptId) {
        return deptMapper.deleteDeptById(deptId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(final List<SysDept> list, final SysDept t) {
        // 得到子节点列表
        final List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (final SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(final List<SysDept> list, final SysDept t) {
        final Long deptId = t.getDeptId();
        return list.stream()
            .filter(FunctionEnhancer.with(SysDept::getParentId).thenTest(deptId::equals))
            .collect(Collectors.toList());
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(final List<SysDept> list, final SysDept t) {
        return list.stream()
            .map(SysDept::getParentId)
            .anyMatch(t.getDeptId()::equals);
    }

    private final ISysDeptService getAopProxy() {
        return SpringUtils.getAopProxy((ISysDeptService)this);
    }
}
